package day11.gec.utils;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JDBCUtil3 {
	
	static Properties p = new Properties();
	public static Connection co;
	public static PreparedStatement s;
	public static ResultSet r;
	
	static {
		try(InputStream is = JDBCUtil3.class.getClassLoader().getResourceAsStream("db.properties")){
			p.load(is);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//提供一个获得连接的方法
	public static Connection getConnection() {
		Connection conn = null;
		try {
			conn = DriverManager.getConnection(p.getProperty("url"), p.getProperty("username"),p.getProperty("password"));
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}
	
	//关闭连接的方法
	public static void closeConn(Connection conn,Statement st ,ResultSet rs) {
		System.out.println("关闭资源....");
		try {
			if(rs != null) {
				rs.close();
			}
			
			if(st != null) {
				st.close();
			}
			
			if(conn != null) {
				conn.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//统一执行添加删除修改的方法
	public static void executeUpdate(String sql,Object[] strs) {
		
		try {
			//获取到连接
			co = getConnection();
			
			//创建语句对象
			s = co.prepareStatement(sql);
			
			int parameterIndex = 1;
			//遍历
			for (Object obj : strs) {
				//给问号设置值
				s.setObject(parameterIndex, obj);
				parameterIndex++;
			}
			
			//执行sql
			s.executeUpdate();//不要传参
			System.out.println("执行的sql:" + s);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}
	
	//统一执行添加删除修改的方法
	public static ResultSet executeQuery(String sql,Object[] strs) {
		
		try {
			//获取到连接
			co = getConnection();
			
			//创建语句对象
			s = co.prepareStatement(sql);
			
			
			
			int parameterIndex = 1;
			//判断
			if(strs != null) {
				//遍历
				for (Object obj : strs) {
					//给问号设置值
					s.setObject(parameterIndex, obj);
					parameterIndex++;
				}
			}
			
			//执行sql
			r = s.executeQuery();//不要传参
			System.out.println("执行的sql:" + s);
			
			return r;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static Connection getCo() {
		return co;
	}

	public static void setCo(Connection co) {
		JDBCUtil3.co = co;
	}

	public static PreparedStatement getS() {
		return s;
	}

	public static void setS(PreparedStatement s) {
		JDBCUtil3.s = s;
	}

	public static ResultSet getR() {
		return r;
	}

	public static void setR(ResultSet r) {
		JDBCUtil3.r = r;
	}
	
	
}
